/*
 * @Description:
 * @Author: dh
 * @Date: 2021-08-19 17:18:39
 * @LastEditors: dh
 * @LastEditTime: 2022-07-15 14:09:11
 */
class EventEmitter {
	constructor() {
		// 事件对象，存放订阅的名字和事件
		this.events = {}
	}
	on(event, callback) {
		// 注意数据，一个名字可以订阅多个事件函数
		this.events[event] = this.events[event] || []
		this.events[event].push(callback)
		return this
	}
	off(event, callback) {
		let callbacks = this.events[event]
		this.events[event] = callbacks && callbacks.filter(fn => fn !== callback)
		return this
	}
	emit(event, ...args) {
		// 遍历执行所有订阅的事件
		let callbacks = this.events[event]
		callbacks.forEach(fn => {
			fn(...args)
		})
		return this
	}
	once(event, callback) {
		const _once = function (...args) {
			callback(...args)
			this.off(event, _once)
		}
		this.on(event, _once)
		return this
	}
}

var em = new EventEmitter()

function workDay(...args) {
	console.log(args) // ['工作8小时']
}
function makeMoney(arg) {
	console.log(arg) // '赚100万'
}
function sayLove() {
	console.log('向喜欢的人示爱')
}
em.on('money', makeMoney)
em.on('love', sayLove)
em.on('work', workDay)

em.emit('money', '赚100万')
em.emit('love')
em.emit('work', '工作8小时')
em.emit('work', '工作10小时')
